package ch.selise.exercise.pattern.notepad.command;

import ch.selise.exercise.pattern.notepad.exception.EmptyStackException;
import ch.selise.exercise.pattern.notepad.exception.ExecuteException;
import ch.selise.exercise.pattern.notepad.exception.UnsupportedCommandException;

public class CommandExecutor {
	
	StackManipulator stackManipulator;
	private static CommandExecutor instance;
	
	public static CommandExecutor getInstance(){
		if(instance == null){
			instance = new CommandExecutor();
		}
		return instance;
	}
	
	private CommandExecutor() {
		this.stackManipulator = new StackManipulator();
	}
	
	/*public void executeCommand(ICommand command) throws ExecuteException{
		try {
			command.execute();
			
			if(command instanceof IUndoableCommand){
				addCommand((IUndoableCommand)command);
			}
			
		} catch (ExecuteException e) {
			//e.printStackTrace();
			throw e;
		}
	}*/
	
	public void executeCommand(GetCommandParameter parameter) throws UnsupportedCommandException, ExecuteException, EmptyStackException
	{
		//IUndoableCommand lastUndoableCommand = null;
		
		
		ICommand command = CommandCreationFactory.getCommand(parameter, stackManipulator);
		if(command != null)
		{
			command.execute();
		}
		if(command instanceof IUndoableCommand){
			 stackManipulator.addCommand((IUndoableCommand)command);
		}
		/*if(command instanceof UndoCommand){
			undoCommand(command);
		}
		if(command instanceof RedoCommand)
		{
			redoCommand(command);
		}*/
	}
	
	/*private void addCommand(IUndoableCommand command) {
		commands.add(command);
	}
	
	public void undoCommand(ICommand command) throws EmptyStackException
	{
		try {
			IUndoableCommand undo = commands.remove(commands.size() - 1);
			//undo.undoCommand();
			//command.execute();
			undoCommands.add(undo);
			//return (IUndoableCommand) undo;
		} catch (Exception e) {
			throw new EmptyStackException("Command Stack is empty", e);
		}
	}
	
	public void redoCommand(ICommand command) throws EmptyStackException
	{
		try {
			IUndoableCommand redo = undoCommands.remove(undoCommands.size() - 1);
			//redo.redoCommand();
			//command.execute();
			commands.add(redo);
			//return (IUndoableCommand) redo;
		} catch (Exception e) {
			throw new EmptyStackException("Undo Command Stack is empty", e);
		}
	}*/

}
